package com.github.cosycode.imgtool.rule;

import com.github.cosycode.common.lang.ShouldNotHappenException;
import com.github.cosycode.common.util.io.IoUtils;
import com.github.cosycode.imgtool.util.FileUtils;
import com.github.cosycode.imgtool.util.HttpUtils;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * <b>Description : </b>
 * <p>
 * <b>created in </b> 2022/8/1
 * </p>
 *
 * @author CPF
 * @since 1.0
 **/
@Data
public class FileBatchExePlan {

    private List<FileExeRecord> list = new ArrayList<>();

    public void addMoveRecord(URI source, String target) {
        list.add(new FileExeRecord(source, FileExeType.MOVE, target));
    }

    public void addDownloadRecord(URI source, File file) {
        list.add(new FileExeRecord(source, FileExeType.DOWNLOAD, file.getPath()));
    }

    public void changeContent(File file, String content) {
        list.add(new FileExeRecord(file.toURI(), FileExeType.CHANGE_CONTENT, content));
    }

    public void appendContent(File file, String content) {
        list.add(new FileExeRecord(file.toURI(), FileExeType.APPEND_CONTENT, content));
    }

    public void execPlan(exeConfig config) throws IOException {
        for (FileExeRecord item : list) {
            FileExeType extType = item.getExtType();
            final File source = new File(item.getFileUri());
            switch (extType) {
                case COPY:
                    FileUtils.moveFile(source, new File(item.getData()), false);
                    break;
                case MOVE:
                    FileUtils.moveFile(source, new File(item.getData()), true);
                    break;
                case DOWNLOAD:
                    HttpUtils.download(source.getPath(), new File(item.getData()), null);
                    break;
                case CHANGE_CONTENT:
                    IoUtils.writeStringToOutputStream(Files.newOutputStream(source.toPath()), item.getData());
                    break;
                default:
                    throw new ShouldNotHappenException("暂不支持该路径");
            }
        }
    }

    public enum FileExeType {
        MOVE, COPY, DOWNLOAD, CHANGE_CONTENT, APPEND_CONTENT
    }

    @Data
    @AllArgsConstructor
    public static class FileExeRecord {
        /**
         * 统一标识定位符号, 用于定位源文件
         */
        private URI fileUri;
        private FileExeType extType;
        /**
         * extType:
         * <p>
         * MOVE: 目标 URI 字符串
         * COPY: 目标 URI 字符串
         * CHANGE_CONTENT: 新文本内容
         * APPEND_CONTENT: 追加内容
         * </p>
         */
        private String data;
    }

    public class exeConfig {
        boolean override;
        boolean rollback;
    }

}
